package push

import (
	"context"
	"fmt"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/LyricTian/jpush-go"

	"im/dao"
	"im/errcode"
	"im/model"
)

var once sync.Once

func Init() {
	once.Do(func() {
		jpush.Init(4,
			jpush.SetAppKey(os.Getenv("JPUSH_APPKEY")),
			jpush.SetMasterSecret(os.Getenv("JPUSH_MASTER_SECRET")))
	})
}
func Terminate() {
	jpush.Terminate()
}
func pushMessageInner(pushToken string, alert string, msgId int, callback jpush.PushResultHandle) error {
	payload := &jpush.Payload{
		Platform:     jpush.NewPlatform().All(),
		Audience:     jpush.NewAudience().SetRegistrationID(pushToken),
		Notification: jpush.NewNotification().SetAlert(alert),
		Options:      jpush.NewOptions().SetSendNO(msgId).SetApnsProduction(os.Getenv("IS_PROD") == "true"),
	}
	return jpush.Push(context.Background(), payload, callback)
}

func PushMessage(pushToken string, alert string) error {
	if pushToken == "" {
		return nil
	}
	msgId := time.Now().Nanosecond()
	var pushLog = model.PushLog{
		StatusCode:   200,
		ErrorMessage: "",
		SendNo:       strconv.Itoa(msgId),
		MessageTitle: alert,
	}
	err := pushMessageInner(pushToken, alert, msgId, func(ctx context.Context, result *jpush.PushResult, err error) {
		if err != nil {
			switch err.(type) {
			case *jpush.Error:
				e := err.(*jpush.Error)
				pushLog.StatusCode = e.StatusCode
				pushLog.ErrorMessage = e.Error()
			default:
				pushLog.StatusCode = 0
				pushLog.ErrorMessage = err.Error()
			}
			errcode.NewError(errcode.JpushErr, err)
			err = dao.NewPushLog().Insert(pushLog)
			return
		}else{
			fmt.Println(result)
		}
	})
	if err != nil {
		return errcode.NewError(errcode.JpushErr, err)
	}
	return err
}
